package com.ogawa.meiditest.activity

import android.Manifest
import android.content.Context
import android.content.IntentFilter
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.midea.iot.sdk.MideaProgressCallback
import com.midea.iot.sdk.MideaSDK
import com.midea.iot.sdk.config.ConfigType
import com.midea.iot.sdk.config.DeviceConfigStep
import com.midea.iot.sdk.config.ap.DeviceApConfigParams
import com.midea.iot.sdk.entity.MideaDevice
import com.midea.iot.sdk.entity.MideaErrorMessage
import com.ogawa.meiditest.databinding.ActivityNetConfigInputBinding
import com.ogawa.meiditest.receiver.OnWifiScanFinishListener
import com.ogawa.meiditest.receiver.WifiBroadcastReceiver
import com.ogawa.meiditest.widget.SoftApPopwindow
import com.ogawa.meiditest.widget.SoftApPopwindowAdapter
import com.yanzhenjie.permission.AndPermission

class NetConnectActivity : BaseActivity(), SoftApPopwindowAdapter.OnItemClickListener {
    private lateinit var binding: ActivityNetConfigInputBinding
    private lateinit var wifiManager: WifiManager
    private lateinit var receiver: WifiBroadcastReceiver
    private lateinit var softApWindow: SoftApPopwindow
    private var scanResult: ScanResult? = null
    private var scanFinish = false

    companion object {
        private const val DEVICE_SSID = "midea_fc_1705"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityNetConfigInputBinding.inflate(layoutInflater)
        setContentView(binding.root)
        wifiManager = application.getSystemService(Context.WIFI_SERVICE) as WifiManager
        receiver = WifiBroadcastReceiver()
        softApWindow = SoftApPopwindow(this, ArrayList(), this)
        receiver.scanFinishListener = object : OnWifiScanFinishListener {
            override fun onScanFinish() {
                if (!scanFinish) {
                    scanFinish = true
                    val scanResults = wifiManager.scanResults
                    
                    Log.e("tag", "------------------------->>${scanResults.size}")
                    softApWindow.update(scanResults)
                    softApWindow.showPopupWindow(binding.etWifiName)
                    dismissLoadingDialog()
                }
            }
        }
        val filter = IntentFilter()
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        registerReceiver(receiver, filter)
        binding.etWifiName.setOnClickListener {
            Log.e("tag", "----------startScan---------------")
            AndPermission.with(this)
                .runtime()
                .permission(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
                .onGranted {
                    scanFinish = false
                    wifiManager.startScan()
                    showLoadingDialog("请稍候")
                }.onDenied { }.start()
        }
        binding.tvNext.setOnClickListener {

            if (scanResult != null) {
                val params = DeviceApConfigParams(
                    this@NetConnectActivity,
                    DEVICE_SSID,
                    scanResult!!.SSID,
                    scanResult!!.capabilities, //加密方式
                    binding.etWifiPsw.text.toString(),
                )
                Log.e(
                    "tag",
                    "----${scanResult!!.SSID}-----------开始配网-----------${scanResult!!.capabilities}-------"
                )
                showLoadingDialog("请稍候")
                MideaSDK.INSTANCE.deviceManager.startConfigureDevice(params, ConfigType.TYPE_AP,
                    object : MideaProgressCallback<MideaDevice, DeviceConfigStep>() {
                        override fun onError(p0: MideaErrorMessage?) {
                            Log.e(
                                "tag",
                                "--${p0?.errorCode}------配网失败-------------->>${p0?.errorMessage}"
                            )
                            Toast.makeText(this@NetConnectActivity, "配网失败", Toast.LENGTH_SHORT)
                                .show()
                            dismissLoadingDialog()
                        }

                        override fun onComplete(p0: MideaDevice?) {
                            Log.e("tag", "---------------配网成功------------------")
                            Toast.makeText(this@NetConnectActivity, "配网成功", Toast.LENGTH_SHORT)
                                .show()
                            dismissLoadingDialog()
                        }

                        override fun onProgressUpdate(p0: DeviceConfigStep?) {
                            Log.e(
                                "tag",
                                "----------${p0?.stepName}-------onProgressUpdate-------------${p0?.step}-----"
                            )
                        }

                    })
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

    override fun onItemClick(scanResult: ScanResult?) {
        this.scanResult = scanResult
        binding.etWifiName.text = scanResult?.SSID
        softApWindow.dismissPopupWindow()
    }

}